package com.fzkjjt.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/**
 * @program: seata-simple
 * @description:
 * @author: FangZhen
 * @create: 2020-10-14 14:56
 **/
@Configuration
public class SeataRestTemplateAutoConfiguration {

    @Autowired(required = false)
    private Collection<RestTemplate> restTemplates;

    @Bean
    public SeataRestTemplateInterceptor seataRestTemplateInterceptor() {
        return new SeataRestTemplateInterceptor();
    }

    @Autowired
    private SeataRestTemplateInterceptor seataRestTemplateInterceptor;

    @PostConstruct
    public void init() {
        if (restTemplates != null) {
            Iterator<RestTemplate> restTemplateIterator = restTemplates.iterator();
            while (restTemplateIterator.hasNext()) {
                RestTemplate restTemplate = restTemplateIterator.next();
                ArrayList<ClientHttpRequestInterceptor> clientHttpRequestInterceptors = new ArrayList<>(restTemplate.getInterceptors());
                clientHttpRequestInterceptors.add(seataRestTemplateInterceptor);
                restTemplate.setInterceptors(clientHttpRequestInterceptors);
            }
        }
    }

}
